<?php
/**
 * 性能优化检查和配置系统
 * Performance Optimization Checker and Configuration System
 * 
 * @package WP Bootstrap Woo
 */

if (!defined('ABSPATH')) {
    exit; // 禁止直接访问
}

/**
 * 性能优化检查器类
 * Performance Optimization Checker Class
 */
class WBW_Performance_Checker {
    
    /**
     * 检查结果
     */
    private $performance_results = array();
    
    /**
     * 优化建议
     */
    private $optimization_suggestions = array();
    
    /**
     * 性能评分
     */
    private $performance_score = 0;
    
    /**
     * 构造函数
     */
    public function __construct() {
        // 初始化
    }
    
    /**
     * 运行完整性能检查
     * 
     * @return array 性能检查结果
     */
    public function run_performance_check() {
        $this->reset_results();
        
        // 1. CSS优化检查
        $this->check_css_optimization();
        
        // 2. JavaScript优化检查
        $this->check_js_optimization();
        
        // 3. 图片优化检查
        $this->check_image_optimization();
        
        // 4. CDN配置检查
        $this->check_cdn_configuration();
        
        // 5. 缓存配置检查
        $this->check_cache_configuration();
        
        // 6. 资源加载策略检查
        $this->check_resource_loading_strategy();
        
        // 7. 移动端优化检查
        $this->check_mobile_optimization();
        
        // 8. 数据库优化检查
        $this->check_database_optimization();
        
        // 计算性能评分
        $this->calculate_performance_score();
        
        return $this->get_performance_results();
    }
    
    /**
     * CSS优化检查
     */
    private function check_css_optimization() {
        $this->add_section('CSS优化检查');
        
        // 检查CSS压缩设置
        $css_optimize = _xin('optimize_css', false);
        if ($css_optimize) {
            $this->add_result('✅ CSS优化已启用', 'success', 10);
        } else {
            $this->add_result('⚠️ CSS优化未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'css_optimize',
                'title' => 'CSS优化建议',
                'description' => '启用CSS优化可以减少文件大小和加载时间',
                'actions' => [
                    '在Codestar Framework中启用CSS优化选项',
                    '检查style-integration.php配置',
                    '验证override-styles.css加载优先级'
                ],
                'benefit' => '可减少CSS文件大小20-40%，提升页面加载速度',
                'priority' => 'high'
            ]);
        }
        
        // 检查CSS文件合并
        $css_combine = _xin('combine_css', false);
        if ($css_combine) {
            $this->add_result('✅ CSS文件合并已启用', 'success', 8);
        } else {
            $this->add_result('⚠️ CSS文件合并未启用', 'warning', 0);
        }
        
        // 检查CSS文件存在性和大小
        $this->check_css_files();
        
        // 检查CSS加载位置
        $this->check_css_loading_position();
        
        // 检查关键CSS
        $this->check_critical_css();
    }
    
    /**
     * JavaScript优化检查
     */
    private function check_js_optimization() {
        $this->add_section('JavaScript优化检查');
        
        // 检查JS压缩设置
        $js_optimize = _xin('optimize_js', false);
        if ($js_optimize) {
            $this->add_result('✅ JavaScript优化已启用', 'success', 10);
        } else {
            $this->add_result('⚠️ JavaScript优化未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'js_optimize',
                'title' => 'JavaScript优化建议',
                'description' => '启用JavaScript优化可以减少文件大小和执行时间',
                'actions' => [
                    '启用JavaScript压缩和合并',
                    '配置template-assets.php的模块化加载',
                    '实现条件式JS加载策略'
                ],
                'benefit' => '可减少JS文件大小30-50%，改善交互响应时间',
                'priority' => 'high'
            ]);
        }
        
        // 检查JS文件合并
        $js_combine = _xin('combine_js', false);
        if ($js_combine) {
            $this->add_result('✅ JavaScript文件合并已启用', 'success', 8);
        } else {
            $this->add_result('⚠️ JavaScript文件合并未启用', 'warning', 0);
        }
        
        // 检查异步加载
        $this->check_js_async_loading();
        
        // 检查延迟加载
        $this->check_js_defer_loading();
        
        // 检查JS文件位置
        $this->check_js_loading_position();
    }
    
    /**
     * 图片优化检查
     */
    private function check_image_optimization() {
        $this->add_section('图片优化检查');
        
        // 检查图片懒加载
        $lazy_load = _xin('lazy_load_images', false);
        if ($lazy_load) {
            $this->add_result('✅ 图片懒加载已启用', 'success', 12);
        } else {
            $this->add_result('⚠️ 图片懒加载未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'lazy_load',
                'title' => '图片懒加载建议',
                'description' => '懒加载可以显著提升页面初始加载速度',
                'actions' => [
                    '在主题设置中启用图片懒加载',
                    '配置lazy loading JavaScript',
                    '为图片添加loading="lazy"属性'
                ],
                'benefit' => '可提升页面加载速度30-60%',
                'priority' => 'medium'
            ]);
        }
        
        // 检查WebP支持
        $webp_support = _xin('webp_support', false);
        if ($webp_support) {
            $this->add_result('✅ WebP格式支持已启用', 'success', 8);
        } else {
            $this->add_result('⚠️ WebP格式支持未启用', 'warning', 0);
        }
        
        // 检查图片压缩设置
        $this->check_image_compression();
        
        // 检查响应式图片
        $this->check_responsive_images();
    }
    
    /**
     * CDN配置检查
     */
    private function check_cdn_configuration() {
        $this->add_section('CDN配置检查');
        
        $cdn_mode = _xin('assets_cdn_mod', 'theme');
        if ($cdn_mode !== 'theme') {
            $this->add_result('✅ CDN加速已启用', 'success', 15);
            
            // 检查CDN域名配置
            $cdn_url = _xin('assets_cdn_url', '');
            if (!empty($cdn_url)) {
                $this->add_result('✅ CDN域名已配置: ' . $cdn_url, 'success', 5);
                
                // 测试CDN连通性
                $this->test_cdn_connectivity($cdn_url);
            } else {
                $this->add_result('⚠️ CDN域名未配置', 'warning', 0);
            }
        } else {
            $this->add_result('⚠️ CDN加速未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'cdn_config',
                'title' => 'CDN配置建议',
                'description' => 'CDN可以显著提升全球用户的访问速度',
                'actions' => [
                    '在type-options.php中配置CDN域名',
                    '选择合适的CDN服务商（如阿里云、腾讯云）',
                    '测试CDN资源加载速度',
                    '配置CDN缓存策略'
                ],
                'benefit' => '可提升静态资源加载速度50-80%',
                'priority' => 'medium'
            ]);
        }
        
        // 检查静态资源CDN覆盖
        $this->check_static_assets_cdn();
    }
    
    /**
     * 缓存配置检查
     */
    private function check_cache_configuration() {
        $this->add_section('缓存配置检查');
        
        // 检查页面缓存
        $page_cache = _xin('enable_page_cache', false);
        if ($page_cache) {
            $this->add_result('✅ 页面缓存已启用', 'success', 10);
        } else {
            $this->add_result('⚠️ 页面缓存未启用', 'warning', 0);
        }
        
        // 检查对象缓存
        if (function_exists('wp_cache_get') && wp_using_ext_object_cache()) {
            $this->add_result('✅ 对象缓存已启用', 'success', 8);
        } else {
            $this->add_result('⚠️ 对象缓存未启用', 'warning', 0);
        }
        
        // 检查浏览器缓存
        $this->check_browser_cache_headers();
        
        // 检查数据库查询缓存
        $this->check_db_query_cache();
    }
    
    /**
     * 资源加载策略检查
     */
    private function check_resource_loading_strategy() {
        $this->add_section('资源加载策略检查');
        
        // 检查条件式加载
        $conditional_loading = _xin('conditional_loading', false);
        if ($conditional_loading) {
            $this->add_result('✅ 条件式资源加载已启用', 'success', 10);
        } else {
            $this->add_result('⚠️ 条件式资源加载未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'conditional_loading',
                'title' => '条件式加载建议',
                'description' => '根据页面类型按需加载资源',
                'actions' => [
                    '在template-assets.php中实现条件判断',
                    '为不同页面类型配置专用资源',
                    '移除不必要的全局资源加载'
                ],
                'benefit' => '可减少不必要的资源加载，提升性能',
                'priority' => 'medium'
            ]);
        }
        
        // 检查预加载设置
        $this->check_resource_preloading();
        
        // 检查资源去重
        $this->check_resource_deduplication();
    }
    
    /**
     * 移动端优化检查
     */
    private function check_mobile_optimization() {
        $this->add_section('移动端优化检查');
        
        // 检查移动端专用资源
        $mobile_optimize = _xin('mobile_optimize', false);
        if ($mobile_optimize) {
            $this->add_result('✅ 移动端优化已启用', 'success', 12);
        } else {
            $this->add_result('⚠️ 移动端优化未启用', 'warning', 0);
            $this->add_optimization_suggestion([
                'type' => 'mobile_optimize',
                'title' => '移动端优化建议',
                'description' => '针对移动设备优化资源加载',
                'actions' => [
                    '创建mobile-responsive.css和mobile-responsive.js',
                    '通过template-assets.php实现移动端专属资源加载',
                    '优化移动端图片尺寸和格式',
                    '减少移动端不必要的功能加载'
                ],
                'benefit' => '可提升移动端用户体验和加载速度',
                'priority' => 'high'
            ]);
        }
        
        // 检查响应式设计
        $this->check_responsive_design();
        
        // 检查移动端缓存
        $this->check_mobile_cache();
        
        // 检查AMP支持
        $this->check_amp_support();
    }
    
    /**
     * 数据库优化检查
     */
    private function check_database_optimization() {
        $this->add_section('数据库优化检查');
        
        // 检查数据库查询优化
        $this->check_db_query_optimization();
        
        // 检查数据库索引
        $this->check_db_indexes();
        
        // 检查自动加载选项
        $this->check_autoload_options();
        
        // 检查数据库清理
        $this->check_db_cleanup();
    }
    
    /**
     * 检查CSS文件
     */
    private function check_css_files() {
        $css_dir = get_template_directory() . '/assets/css';
        $css_files = [
            'plugin.css' => '插件样式',
            'feather.css' => '图标样式',
            'collection.css' => '商品集合样式',
            'style1.css' => '主题样式'
        ];
        
        $total_size = 0;
        $missing_files = 0;
        
        foreach ($css_files as $file => $description) {
            $file_path = $css_dir . '/' . $file;
            if (file_exists($file_path)) {
                $size = filesize($file_path);
                $total_size += $size;
                $size_kb = round($size / 1024, 2);
                $this->add_result("✅ {$description} 存在 ({$size_kb} KB)", 'success', 2);
            } else {
                $missing_files++;
                $this->add_result("❌ {$description} 缺失", 'error', 0);
            }
        }
        
        if ($total_size > 0) {
            $total_kb = round($total_size / 1024, 2);
            if ($total_kb > 200) {
                $this->add_result("⚠️ CSS文件总大小过大: {$total_kb} KB", 'warning', 0);
            } else {
                $this->add_result("✅ CSS文件大小合理: {$total_kb} KB", 'success', 3);
            }
        }
    }
    
    /**
     * 检查CSS加载位置
     */
    private function check_css_loading_position() {
        // 检查关键CSS是否内联
        $inline_critical_css = _xin('inline_critical_css', false);
        if ($inline_critical_css) {
            $this->add_result('✅ 关键CSS内联加载已启用', 'success', 5);
        } else {
            $this->add_result('⚠️ 关键CSS内联加载未启用', 'warning', 0);
        }
    }
    
    /**
     * 检查关键CSS
     */
    private function check_critical_css() {
        $critical_css_file = get_template_directory() . '/assets/css/critical.css';
        if (file_exists($critical_css_file)) {
            $this->add_result('✅ 关键CSS文件存在', 'success', 5);
        } else {
            $this->add_result('⚠️ 关键CSS文件不存在', 'warning', 0);
        }
    }
    
    /**
     * 测试CDN连通性
     * 
     * @param string $cdn_url CDN URL
     */
    private function test_cdn_connectivity($cdn_url) {
        $test_url = rtrim($cdn_url, '/') . '/test-connectivity';
        $response = wp_remote_get($test_url, array('timeout' => 5));
        
        if (is_wp_error($response)) {
            $this->add_result('⚠️ CDN连通性测试失败', 'warning', 0);
        } else {
            $status_code = wp_remote_retrieve_response_code($response);
            if ($status_code === 200) {
                $this->add_result('✅ CDN连通性正常', 'success', 3);
            } else {
                $this->add_result("⚠️ CDN响应异常 (状态码: {$status_code})", 'warning', 0);
            }
        }
    }
    
    /**
     * 计算性能评分
     */
    private function calculate_performance_score() {
        $total_possible = 0;
        $actual_score = 0;
        
        foreach ($this->performance_results as $result) {
            if (isset($result['score'])) {
                $total_possible += $result['max_score'] ?? $result['score'];
                $actual_score += $result['score'];
            }
        }
        
        if ($total_possible > 0) {
            $this->performance_score = round(($actual_score / $total_possible) * 100, 2);
        } else {
            $this->performance_score = 0;
        }
    }
    
    /**
     * 添加检查结果
     * 
     * @param string $message 消息
     * @param string $type 类型
     * @param int $score 得分
     * @param int $max_score 最大得分
     */
    private function add_result($message, $type = 'info', $score = 0, $max_score = null) {
        $this->performance_results[] = array(
            'message' => $message,
            'type' => $type,
            'score' => $score,
            'max_score' => $max_score ?? $score,
            'timestamp' => current_time('timestamp')
        );
    }
    
    /**
     * 添加检查节
     * 
     * @param string $title 节标题
     */
    private function add_section($title) {
        $this->performance_results[] = array(
            'type' => 'section',
            'title' => $title,
            'timestamp' => current_time('timestamp')
        );
    }
    
    /**
     * 添加优化建议
     * 
     * @param array $suggestion 优化建议
     */
    private function add_optimization_suggestion($suggestion) {
        $this->optimization_suggestions[] = $suggestion;
    }
    
    /**
     * 重置结果
     */
    private function reset_results() {
        $this->performance_results = array();
        $this->optimization_suggestions = array();
        $this->performance_score = 0;
    }
    
    /**
     * 获取性能检查结果
     * 
     * @return array 完整的性能检查结果
     */
    public function get_performance_results() {
        return array(
            'performance_score' => $this->performance_score,
            'results' => $this->performance_results,
            'optimization_suggestions' => $this->optimization_suggestions,
            'summary' => $this->get_performance_summary(),
            'timestamp' => current_time('timestamp')
        );
    }
    
    /**
     * 获取性能摘要
     * 
     * @return array 性能摘要
     */
    private function get_performance_summary() {
        $total_checks = count($this->performance_results);
        $errors = count(array_filter($this->performance_results, function($r) { return $r['type'] === 'error'; }));
        $warnings = count(array_filter($this->performance_results, function($r) { return $r['type'] === 'warning'; }));
        $successes = count(array_filter($this->performance_results, function($r) { return $r['type'] === 'success'; }));
        
        return array(
            'total_checks' => $total_checks,
            'errors' => $errors,
            'warnings' => $warnings,
            'successes' => $successes,
            'optimization_opportunities' => count($this->optimization_suggestions)
        );
    }
    
    /**
     * 应用自动优化
     * 
     * @param array $optimization_types 要应用的优化类型
     * @return array 应用结果
     */
    public function apply_auto_optimizations($optimization_types = array()) {
        $results = array();
        
        foreach ($optimization_types as $type) {
            switch ($type) {
                case 'css_optimize':
                    $results[$type] = $this->enable_css_optimization();
                    break;
                case 'js_optimize':
                    $results[$type] = $this->enable_js_optimization();
                    break;
                case 'lazy_load':
                    $results[$type] = $this->enable_lazy_loading();
                    break;
                case 'mobile_optimize':
                    $results[$type] = $this->enable_mobile_optimization();
                    break;
                default:
                    $results[$type] = array('status' => 'error', 'message' => '未知的优化类型');
            }
        }
        
        return $results;
    }
    
    /**
     * 启用CSS优化
     */
    private function enable_css_optimization() {
        try {
            // 通过Codestar Framework保存设置
            $options = get_option('_xin_options', array());
            $options['optimize_css'] = true;
            $options['combine_css'] = true;
            update_option('_xin_options', $options);
            
            return array('status' => 'success', 'message' => 'CSS优化已启用');
        } catch (Exception $e) {
            return array('status' => 'error', 'message' => '启用CSS优化失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 启用JS优化
     */
    private function enable_js_optimization() {
        try {
            $options = get_option('_xin_options', array());
            $options['optimize_js'] = true;
            $options['combine_js'] = true;
            update_option('_xin_options', $options);
            
            return array('status' => 'success', 'message' => 'JavaScript优化已启用');
        } catch (Exception $e) {
            return array('status' => 'error', 'message' => '启用JavaScript优化失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 启用懒加载
     */
    private function enable_lazy_loading() {
        try {
            $options = get_option('_xin_options', array());
            $options['lazy_load_images'] = true;
            update_option('_xin_options', $options);
            
            return array('status' => 'success', 'message' => '图片懒加载已启用');
        } catch (Exception $e) {
            return array('status' => 'error', 'message' => '启用懒加载失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 启用移动端优化
     */
    private function enable_mobile_optimization() {
        try {
            $options = get_option('_xin_options', array());
            $options['mobile_optimize'] = true;
            update_option('_xin_options', $options);
            
            return array('status' => 'success', 'message' => '移动端优化已启用');
        } catch (Exception $e) {
            return array('status' => 'error', 'message' => '启用移动端优化失败: ' . $e->getMessage());
        }
    }
    
    // 其他检查方法的占位符（简化版本）
    private function check_js_async_loading() {
        // JavaScript异步加载检查
    }
    
    private function check_js_defer_loading() {
        // JavaScript延迟加载检查
    }
    
    private function check_js_loading_position() {
        // JavaScript加载位置检查
    }
    
    private function check_image_compression() {
        // 图片压缩检查
    }
    
    private function check_responsive_images() {
        // 响应式图片检查
    }
    
    private function check_static_assets_cdn() {
        // 静态资源CDN检查
    }
    
    private function check_browser_cache_headers() {
        // 浏览器缓存头检查
    }
    
    private function check_db_query_cache() {
        // 数据库查询缓存检查
    }
    
    private function check_resource_preloading() {
        // 资源预加载检查
    }
    
    private function check_resource_deduplication() {
        // 资源去重检查
    }
    
    private function check_responsive_design() {
        // 响应式设计检查
    }
    
    private function check_mobile_cache() {
        // 移动端缓存检查
    }
    
    private function check_amp_support() {
        // AMP支持检查
    }
    
    private function check_db_query_optimization() {
        // 数据库查询优化检查
    }
    
    private function check_db_indexes() {
        // 数据库索引检查
    }
    
    private function check_autoload_options() {
        // 自动加载选项检查
    }
    
    private function check_db_cleanup() {
        // 数据库清理检查
    }
}